<?php

//用户管理
namespace App\Http\Controllers\Admin;

use App\Models\User;
use Illuminate\Http\Request;
use Mail;
use Hash;
use App\Models\Role;

class UserController extends BaseController
{
    //用户列表
    public function index() {
        //分页  倒序排，添加用户成功后重定向到这里能第一时间看到
        $data = User::orderBy('id', 'desc')->withTrashed()->paginate($this->item_num_per_page);

        return view('admin.user.index', compact('data'));
    }

    public function create()
    {
        return view('admin.user.create');
    }

    public function store(Request $request)
    {
        $rules = [
            'username' => 'required|unique:users,username', //检查唯一性 unique:表名,字段名
            'truename' => 'required',
            'password' => 'required|confirmed',
            'phone' => 'nullable|myphone', //只有写了才需要验证 自定义规则 定义在app\Providers\AppServiceProvider.php
        ];
//        $msg = [
//            'phone.myphone' => '手机号码不合法(自定义msg)'
//        ]; 找resources/lang/zh-CN/validation.php 写 'myphone'               => ':attribute 号码不合法(validation.php)',
        $this->validate($request, $rules);
//        dump($request->all());


        //入库前查模型有没有设置黑白名单
        //获取表单数据
        $post = $request->except(['_token', 'password_confirmation']);
        //入库
        $userModel = User::create($post);
        $pwd = $post['password'];
        //dump($userModel->toArray());//展示了\App\Models\User的实例

        //发邮件给用户
        Mail::send('mail.useradd', compact('userModel', 'pwd'), function($message) use($userModel) {
            $message->subject('开通账号邮件通知');
            $message->to($userModel->email);
        });

        //跳转到
        return redirect(route('admin.user.index'))->with('success', '添加用户成功');
    }

    //删除用户操作
    public function del(int $id) {
        //当前是软删除(User模型配置了软删除)
        dd('第二步');
        User::find($id)->delete();
        //强制删除(在配置了软删除的时候，真删除)
        //User::find($id)->forceDelete();

        return ['status' => 0, 'msg' => "删除{$id}成功"];
    }

    //还原已软删除用户
    public function restore(int $id) {
        User::onlyTrashed()->find($id)->restore();
        return redirect(route('admin.user.index'))->with('success', '还原用户成功');
    }

    public function delall(Request $request) {
        $ids = $request->get('ids');
        User::destroy($ids);
        return ['status' => 0, 'msg' => "全选删除成功"];
    }

    //修改：显示
    public function edit(int $id) {
        $model = User::find($id);

        return view('admin.user.edit', compact('model'));
    }

    //修改：处理
    public function update(Request $request, int $id) {
        $model = User::find($id);
        //原密码 明文
        $spass = $request->get('spassword');
        //原密码  密文
        $oldpass =$model->password;
        //检查明文和密文是否一致
        $ret = Hash::check($spass, $oldpass);

        if ($ret) {
            //修改
            $data = $request->only([
                'truename',
                'password',
                'phone',
                'sex',
                'email'
            ]);
            if (!empty($data['password'])) {
                //设置了password 就加密，参与到更新
                $data['password'] = bcrypt($data['password']);
            } else {
                //没设置password 就不参与更新
                unset($data['password']);
            }


            $model->update($data);
            return redirect(route('admin.user.index', $model))->with(['success'=>'修改用户成功']);
        }

        return redirect(route('admin.user.edit', $model))->withErrors(['error'=>'原密码不正确']);
    }

    //分配角色和处理
    public function role(Request $request, User $user) {
        if ($request->isMethod('post')) {
//            dd($request->get('role_id'));
            $post = $this->validate($request, [
                'role_id' => 'required'
            ], [
                'role_id.required' => '必须选择'
            ]);

            $user->update($post);
            return redirect(route('admin.user.index'));
        }
        //读取所有角色
        $roleAll = Role::all();
        return view('admin.user.role', compact('user', 'roleAll'));
    }
}
